﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CommerceOne.Common;
using CommerceOne.Controllers;

namespace CommerceOne.Widgets.HeroImage
{
    public class HeroImageController : ControllerBase
    {
        /// <summary>
        /// Gets the view model.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public HeroImageViewModel GetViewModel(int? id)
        {
            string configPath = @"~\Configurations\HeroImages.xml";
            configPath = this.HttpContextBase.Server.MapPath(configPath);

            Configurations configuration = SerializeService.Instance.DeserializeObject<Configurations>(configPath);

            HeroImageViewModel viewModel = new HeroImageViewModel();
            if (configuration == null) throw new Exception("Config file doesnot existed. Check file: " + configPath);

            viewModel.Address = configuration.Link;

            if (!id.HasValue)
            {
                viewModel.Image = configuration.HeroImages.FirstOrDefault(p => p.ID == 0);
            }
            else
            {
                viewModel.Image = configuration.HeroImages.FirstOrDefault(p => p.ID == id.Value);
                if (viewModel.Image == null)
                    viewModel.Image = configuration.HeroImages.FirstOrDefault(p => p.ID == 0);
            }

            if (viewModel.Image != null)
                viewModel.Image.ImageUrl = DisplayUtil.GetImageUrl(viewModel.Image.ImageUrl);

            return viewModel;
        }

        #region Singleton Instance
        private static HeroImageController _instance;

        public static HeroImageController Instance
        {
            get
            {
                if (_instance == null) _instance = new HeroImageController();
                return _instance;
            }
        }

        #endregion

    }
}